<?php
/**
 * User: madis
 * Date: 25.09.2009
 * Time: 22:09:54
 */

function __autoload($className) {
    require_once($className.'.php');
}


class OIS2iCal {

    private $XMLContent;
    private $icsContent;
    private $userName;
    private $password;

    public function getXMLContent() {
        $oisParser = new OISParser($this->userName, $this->password);
        //echo 'Successfully logged in.<br />';
        $xmlContent = $oisParser->getXMLContent();
        //echo 'Successfully received xml.<br />';
        $this->XMLContent = $xmlContent;
    }

    public function getICSContent() {
        $icsConverter = new ICSConverter($this->XMLContent);
        //echo 'Successfully converted xml to ics.<br />';
        $icsContent = $icsConverter->getICSContent();
        $this->icsContent = $icsContent;
    }

    public function run() {
        $this->getXMLContent();
        $this->getICSContent();
        $this->writeICSFile('my_calendar.ics');
    }

    public function writeICSFile($fileName= 'testFile.ics') {
        //$fileHandle = fopen($fileName, 'w');
        //fwrite($fileHandle, stripslashes($this->icsContent));
        //fclose($fileHandle);
        echo stripslashes($this->icsContent);
        //echo 'Successfully writed ics file <b>'.$fileName.'</b> to disk.<br />';

        //$currentPath = $_SERVER['HTTP_HOST'].'/'.dirname($_SERVER['PHP_SELF']).'/';
        //header('location:http://'.$currentPath.$fileName);

        // We will be outputting a PDF
        header('Content-type: text/calendar');
        // It will be called downloaded.pdf
        header('Content-Disposition: attachment; filename="'.$fileName.'"');
        // The source
        //readfile($fileName);
    }

    public function show() {
        if (!isset($_POST['user_name']) || !isset($_POST['password'])) {
            new FrontEnd();
        } else {
            $this->userName = addslashes($_POST['user_name']);
            $this->password = addslashes($_POST['password']);

            try {
                $this->run();
            } catch (Exception $e) {
                echo $e->getMessage();
                new FrontEnd();
            }
        }

    }

}

$OIS2iCal = new OIS2iCal();
$OIS2iCal->show();
